<?php

/**
 * @desc Insert parameters into a string with sprintf but formerly escape functional HTML characters ('<', '"')
 */
function htmlformat($str) {
	$args = array_map('htmlencode', func_get_args());
	$args[0] = $str;
	return call_user_func_array('sprintf', $args);
}

/**
 * @desc HTML encode entities using the default encoding
 */
function &htmlencode($str) {
	return htmlentities($str, ENT_COMPAT|ENT_HTML5, encoding());
}

/**
 * @desc Replace special chars but maintain html functional characters like '<', '&' and '"'
 */
function htmltextentities($string, $encoding = NULL) {
	static $table;
	if (!isset($table)) {
		$table = get_html_translation_table(HTML_ENTITIES, ENT_COMPAT|ENT_HTML5, isset($encoding) ? $encoding : encoding());
		$skip = array("<", ">", "'", '"', "=", "/", "&");
		foreach ($skip as $char) unset($table[$char]);
	}
	return str_replace(array_keys($table), array_values($table), $string);
}

/**
 * @desc Add HTML code to the page's <head> tag
 */
function htmlhead($str = NULL) {
	static $head = '';
	if (func_num_args() > 0) {
		$head .= ($head ? "\n" : '').$str;
		return $str;
	}
	return $head;
}

/**
 * @desc Add a <link> element to the page head
 */
function htmllink($href, $rel = 'stylesheet', $type = 'text/css') {
	return htmlhead('<link href="'.htmlentities($href).'" rel="'.htmlentities($rel).'" type="'.htmlentities($type).'"/>'."\n");
}

/**
 * @desc Add a <script> element to the page head
 */
function htmlscript($src, $type = 'text/javascript') {
	return htmlhead('<script src="'.htmlentities($src).'" type="'.htmlentities($type).'"></script>'."\n");
}

/**
 * @desc Specify the JavaScript action to be executed when the page has finished loading
 */
function htmlonload($str = NULL) {
	static $onload;
	if (func_num_args() > 0) $onload = $str;
	return $onload;
}
